// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

/// User-defined extension types.
/// \since 0.13.0

#pragma once

#include <memory>
#include <string>

#include <nebula/array/array_base.h>
#include <nebula/array/data.h>

#include <turbo/utility/status.h>
#include <nebula/types/type.h>
#include <nebula/types/type_fwd.h>
#include <turbo/base/checked_cast.h>
#include <turbo/base/macros.h>

namespace nebula {

    /// \brief The base class for custom / user-defined types.
    class TURBO_EXPORT ExtensionType : public DataType {
    public:
        static constexpr Type::type type_id = Type::EXTENSION;

        static constexpr const char *type_name() { return "extension"; }

        /// \brief The type of array used to represent this extension type's data
        const std::shared_ptr<DataType> &storage_type() const { return storage_type_; }

        /// \brief Return the type category of the storage type
        Type::type storage_id() const override { return storage_type_->id(); }

        DataTypeLayout layout() const override;

        std::string to_string(bool show_metadata = false) const override;

        std::string name() const override { return "extension"; }

        int32_t byte_width() const override { return storage_type_->byte_width(); }

        int bit_width() const override { return storage_type_->bit_width(); }

        /// \brief Unique name of extension type used to identify type for
        /// serialization
        /// \return the string name of the extension
        virtual std::string extension_name() const = 0;

        /// \brief Determine if two instances of the same extension types are
        /// equal. Invoked from ExtensionType::Equals
        /// \param[in] other the type to compare this type with
        /// \return bool true if type instances are equal
        virtual bool ExtensionEquals(const ExtensionType &other) const = 0;

        /// \brief Wrap built-in Array type in a user-defined ExtensionArray instance
        /// \param[in] data the physical storage for the extension type
        virtual std::shared_ptr<Array> make_array(std::shared_ptr<ArrayData> data) const = 0;

        /// \brief create an instance of the ExtensionType given the actual storage
        /// type and the serialized representation
        /// \param[in] storage_type the physical storage type of the extension
        /// \param[in] serialized_data the serialized representation produced by
        /// serialize
        virtual turbo::Result<std::shared_ptr<DataType>> deserialize(
                std::shared_ptr<DataType> storage_type,
                const std::string &serialized_data) const = 0;

        /// \brief create a serialized representation of the extension type's
        /// metadata. The storage type will be handled automatically in IPC code
        /// paths
        /// \return the serialized representation
        virtual std::string serialize() const = 0;

        /// \brief Wrap the given storage array as an extension array
        static std::shared_ptr<Array> WrapArray(const std::shared_ptr<DataType> &ext_type,
                                                const std::shared_ptr<Array> &storage);

        /// \brief Wrap the given chunked storage array as a chunked extension array
        static std::shared_ptr<ChunkedArray> WrapArray(
                const std::shared_ptr<DataType> &ext_type,
                const std::shared_ptr<ChunkedArray> &storage);

    protected:
        explicit ExtensionType(std::shared_ptr<DataType> storage_type)
                : DataType(Type::EXTENSION), storage_type_(storage_type) {}

        std::shared_ptr<DataType> storage_type_;
    };

    /// \brief Base array class for user-defined extension types
    class TURBO_EXPORT ExtensionArray : public Array {
    public:
        using TypeClass = ExtensionType;

        /// \brief Construct an ExtensionArray from an ArrayData.
        ///
        /// The ArrayData must have the right ExtensionType.
        explicit ExtensionArray(const std::shared_ptr<ArrayData> &data);

        /// \brief Construct an ExtensionArray from a type and the underlying storage.
        ExtensionArray(const std::shared_ptr<DataType> &type,
                       const std::shared_ptr<Array> &storage);

        const ExtensionType *extension_type() const {
            return turbo::checked_cast<const ExtensionType *>(data_->type.get());
        }

        /// \brief The physical storage for the extension array
        const std::shared_ptr<Array> &storage() const { return storage_; }

    protected:
        void set_data(const std::shared_ptr<ArrayData> &data);

        std::shared_ptr<Array> storage_;
    };

    class TURBO_EXPORT ExtensionTypeRegistry {
    public:
        /// \brief Provide access to the global registry to allow code to control for
        /// race conditions in registry teardown when some types need to be
        /// unregistered and destroyed first
        static std::shared_ptr<ExtensionTypeRegistry> GetGlobalRegistry();

        virtual ~ExtensionTypeRegistry() = default;

        virtual turbo::Status register_type(std::shared_ptr<ExtensionType> type) = 0;

        virtual turbo::Status UnregisterType(const std::string &type_name) = 0;

        virtual std::shared_ptr<ExtensionType> get_type(const std::string &type_name) = 0;
    };

    /// \brief Register an extension type globally. The name returned by the type's
    /// extension_name() method should be unique. This method is thread-safe
    /// \param[in] type an instance of the extension type
    /// \return turbo::Status
    TURBO_EXPORT
    turbo::Status RegisterExtensionType(std::shared_ptr<ExtensionType> type);

    /// \brief Delete an extension type from the global registry. This method is
    /// thread-safe
    /// \param[in] type_name the unique name of a registered extension type
    /// \return turbo::Status error if the type name is unknown
    TURBO_EXPORT
    turbo::Status UnregisterExtensionType(const std::string &type_name);

    /// \brief Retrieve an extension type from the global registry. Returns nullptr
    /// if not found. This method is thread-safe
    /// \return the globally-registered extension type
    TURBO_EXPORT
    std::shared_ptr<ExtensionType> GetExtensionType(const std::string &type_name);

    TURBO_EXPORT extern const char kExtensionTypeKeyName[];
    TURBO_EXPORT extern const char kExtensionMetadataKeyName[];

}  // namespace nebula
